package com.dailyblue.java.servlet.controller;

import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;

// 验证码
@WebServlet("/captcha")
public class CaptchaController extends ReflectionController {
    private String str = "";

    @SneakyThrows
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        str = "";
        // 生成一张图片
        BufferedImage image = new BufferedImage(120, 20, BufferedImage.TYPE_INT_RGB);
        // 生成一支笔
        Graphics graphics = image.getGraphics();
        // 设置笔的颜色 rgb:0-255
        Color c1 = new Color(234, 211, 208);
        graphics.setColor(c1);
        // 填充
        graphics.fillRect(0, 0, 120, 20);
        // 在图片上书写文字
        int x = 20;
        for (int i = 0; i < 4; i++) {
            // A-Z的随机字母
            char ch = (char) ((int) (Math.random()* 26 + 65) ); // ASCII:A-65
            // 随机的一个颜色
            int red = (int) (Math.random() * 256);
            int green = (int) (Math.random() * 256);
            int blue = (int) (Math.random() * 256);
            Color color = new Color(red, green, blue);
            graphics.setColor(color);
            graphics.drawString(ch + "", x, 12);
            x += 20;
            str += ch;
        }
        request.getSession().setAttribute("YZM",str);
        System.out.println("生成的验证码是：" + str);
        // 输出图片
        ImageIO.write(image, "JPG", response.getOutputStream());
    }
}
